<template>
  <div class='box-wrap-total'>
    <section class='box-operation'>
      <div class="box-search">        
        <div class='form-group-enquire-date'>
          <DatePicker type="daterange" placeholder="注册时间" :editable=false v-model="searchDate" @on-change="changeDate" @on-clear="initDate"></DatePicker>                   
        </div>         
        <div class='form-group-img' @click='onSearchGetList()'><img src="../../assets/images/peach-svg/Frame 23.svg"></div>
        <div class='form-group-addimg' @click='downloadFile()'><img src="../../assets/images/peach-svg/export.svg"></div>
      </div>
    </section>
    <LibVxeTable class="staticData" :stripe="stripe" :show-footer="showFooter" :footer-method="footerMethodFunc" border="none" :tableColumns="tableColumns" :tableData="list" :slotHeader="slotHeader" :PageObj="{total:totalCnt,currentPage:searchData.page_index,pageSize:searchData.page_size}"  @onPageChange="onChangePageSize" resizable></LibVxeTable>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import utils from "../../commons/utils";
import {commonMixin} from "../../components/ViewInitMixin" //每一个文件都要包含这个
import {TimePicker} from "iview"
import SearchUser from "../searchUser"
import {ACDN} from '../../commons/staticName'
import Request from "../../commons/Request"

export default {
  name: "addUserDetailView",  //!!这块一定要注意，每一个文件都根据资源path来命名
  components:{TimePicker,SearchUser},
  mixins:[commonMixin],
  data() {
    return {
      stripe:false,      
      statuslist: [{id:1,name:'正常'},{id:2,name:'冻结'}],
      modal:false,
      searchDate:"",
      searchTime:[utils.dateFormat(0,"HH")+"00",utils.dateFormat(0,"HH")+"00"],
      searchData:{
        start:"",
        end:"",
      },
      list:[],
      totalCnt:0,
      info:{},
      roles:[],
      footerMethod:{},
      leaders:[],
      roleList:{},
      rollist:[],
      leaderlist:[],
      eid:"",
      tableColumns:[
        {
          title: "ID",
          field: "id",
          align: 'center',
        },
        {
          title: "充值日期",
          field: "date",
          align: 'center',
        },
        {
          title: "充值总额",
          field: "recharge_total",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.recharge_total==0){
                return [h("div",'-')]
              }else
              return [h("div",row.recharge_total/10000)]
            }
          }
        },
        {
          title: "赠送积分总额",
          field: "points_gift",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.points_gift==0){
                return [h("div",'-')]
              }else
              return [h("div",row.points_gift/10000)]
            }
          }
        },       
      ],
      format: {  
        account:{
          labelName: "账号",
          labelType: "text",      
          placeholder:"请输入账号"
        },
        passwd:{
          labelName: "密码",
          labelType: "password",     
          placeholder:"请输入密码"          
        },
        role_id:{
          labelName: "用户角色",
          labelType: "select",
          labelValue:[],          
          placeholder:"请选择角色" 
        },
        leader_id:{
          labelName: "代理商",
          labelType: "select",
          labelValue:[],          
          placeholder:"请选择代理商"  
        }                
      },       
      ruleValidate: {
      },      
      dateOptions:{
        disabledDate(date){
          return date && date.valueOf() > Date.now();
        },

      },
    };
  },
  computed: {
            ...mapGetters(["UserInfo"]),
        },
  methods: {
    async initView(isMounted){
      if(isMounted){
        this.initDate();        
        await this.getList();
        await this.initSearchData();
      }

    },
    async initSearchData() {
      let roles = await this.RequestPost("queryRoles_list");
      let leaders = await this.RequestPost("queryLeaders_list");
      console.log(leaders);
      //角色
      if(roles.data!=null){
        roles.data.list.forEach((item) => {
          this.rollist.push(item)
          this.$set(this.roleList,item.role_id,item.role_name)
          this.format.role_id.labelValue.push({id:item.role_id,name:item.role_name});
        })        
      } 
      //上级
      if(leaders.data!=null){
        leaders.data.list.forEach((item) => {
          this.leaderlist.push(item)
          this.format.leader_id.labelValue.push({id:item.id,name:item.account});
        })        
      }  
    },
    onSearchGetList(){
      this.searchData.page_index =1;
      this.getList();
    },
    async getList(){
      utils.showLoading()
      let res = await this.RequestPost("query_list",this.searchData);
      console.log(res,'srea');     
      if(res.code==0 && res.data != null){
        this.list = [];
        if(res.data.list!=null) this.list = res.data.list;
        this.totalCnt = res.data.total
      }
      await utils.sleepMs(500)
      utils.hideLoading();
    },    
    //添加 编辑用户
    async editInfo(row,type) {
      this.eid = row.id
      this.handleType=type;
      let title = "";
      let info = {};
      if(this.handleType==1){
        title = "添加用户";
        info = {
        };
      }else if(this.handleType==2){
        console.log('1');
        if (row.status > 1){
          this.format.Status.labelDisabled = true
        }
        title = "编辑用户";
        info = {      
        };
      }else if(this.handleType==3){
        this.format.account.labelDisabled = true
        title = "修改密码";
        info = {    
        };
      }
      this.formPopIndex=await utils.showFormPage(
        { title: title,el:this.$parent.$el,width:700,cancelBtnStatus:0},
        info,
        this.format,
        this.ruleValidate,
        this.updateInfo,
        this.onSelectChange,
      );
      this.getList()
    },      
    async updateInfo(info) {
      utils.showLoading()
      let code = -1;
      let actionName = '';
      let tipText = '';
      let postData = utils.cloneObj(info);
      console.log(postData,'upda');
      if (this.handleType==1) {
        actionName = 'add_item';
        tipText = '添加成功！';  
      }else if(this.handleType==2){
        actionName = 'edit_item';
        tipText = '编辑成功！';     
        postData = {"id":this.eid,"account":postData.account,"role_id":postData.role_id};
        delete postData.PurchaseType
      }else if(this.handleType==-1){
        actionName = 'del_item';
        tipText = '删除成功！';
        postData = {"id":postData.Id};
      }else if(this.handleType==3){
        actionName = 'resetPasswd_item';
        tipText = '修改密码成功';
        postData = {"id":this.eid,"passwd":postData.passwd};
      }    
      let res = await this.RequestPost(actionName, postData);
      code = res.code;
      if (code == 0) {
        utils.hideFormPage(this.formPopIndex);
        await utils.sleepMs(1000);
        utils.showTip(tipText);
      }
      utils.hideLoading();
      this.getList()      
    },         
    //删除
    sureDel(item,type) {
       this.handleType = -1;
        utils.showSureModal({
          "title":"删除提示",            
          "icon":require('../../assets/images/peach-svg/Frame 427318277 (1).svg'),
          "modalContent":"确认删除 "+item.id+" ?","callBackArgs":{"Id":item.id}},(res)=>{
        let code = res.code;
        if(code==0){
          let data = res.data;
          this.updateInfo(data);
        }
      });
      this.getList()
    },    
    onChangePageSize(page,pageSize){
      this.modal = true        
      this.searchData.page_index = page;
      this.searchData.page_size = pageSize;
      this.getList();
    },
    //日期
    initDate(){
      let beginDay,endDay=""
      this.searchDate=[new Date(beginDay),new Date(endDay)]
      this.changeDate();
    },  
    changeDate(){
      this.searchData.start = Date.parse(this.searchDate[0])/1000
      this.searchData.end = Date.parse(this.searchDate[1])/1000+86400
    },          
    onSelectChange(label,value,reset){
      console.log(label,'onSelectChange');
      console.log(value,'onSelectChange');
    },    
    slotHeader(h) {
      return [h("div",{class:{"allCount":true},"style":{"margin-left":"10px"}})]
    },
    //导出
    async downloadFile() {
      utils.showLoading("正在生成中")
      let res = await this.RequestPost("edit_exportData",this.searchData);
      if(res.code==0){
        utils.hideLoading()
          await utils.sleepMs(500);
          utils.showTip("导出成功，在IM中查收");
      }
      window.open(ACDN + res.data)
    },     
    //总计
    footerMethodFunc({ columns, data }){
      return [columns.map((item,index) => {
          if(index ==0){
            return '总计'
          }else if(['充值总额','赠送积分总额'].includes(item.title)){
            return this.unitprice(data)
          }
          return null
        })
      ]
    },    
    unitprice(data){
      let recharge_total = 0
      data.forEach(item =>{
        recharge_total+=item.recharge_total
      })
      return recharge_total
    },
    showFooter(){
     if(this.footerMethod){
         return true;
     }else{
         return false;
     }      
    } 
  },
};
</script>  